package cn.edu.ujn.park.controller;

import cn.edu.ujn.park.dao.Coupon;
import cn.edu.ujn.park.service.ICouponService;
import cn.edu.ujn.util.Page;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class CouponController {
    @Autowired
    private ICouponService couponService;

    @GetMapping("/coupon")
    public String list(Model model, @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "rows", defaultValue = "10") Integer rows, Coupon coupon, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Integer userId = (Integer) session.getAttribute("userId");  //获取当前用户
        coupon.setUserId(userId);
        coupon.setStart((page - 1) * rows);
        coupon.setRows(rows);
        Page<Coupon> page1 = couponService.selectByUserId(coupon);
        model.addAttribute("page", page1);
        return "coupon";
    }

    @PostMapping("/couponAcquire")
    public String acquire(Model model, @RequestParam(value = "code") String code,
                          @RequestParam(value = "page", defaultValue = "1") Integer page,
                          @RequestParam(value = "rows", defaultValue = "10") Integer rows,
                          HttpServletRequest request, Coupon coupon) {
        HttpSession session = request.getSession();
        Integer userId = (Integer) session.getAttribute("userId");
        coupon.setUserId(userId);
        coupon.setCode(code);
        Integer i =  couponService.acquireCoupon(coupon);
        if (i <= 0) {
            model.addAttribute("msg", "优惠券码错误或已被兑换！");
        } else {
            model.addAttribute("msg", "兑换成功！");
        }
        return list(model, page, rows, coupon, request);
    }

    /*public String list(Model model, @RequestParam(value = "page",defaultValue = "1") Integer page,
                       @RequestParam(value = "row",defaultValue = "10")Integer rows, Coupon coupon ) {
        coupon.setStart((page-1)*rows);
        coupon.setRows(rows);
        Page<Coupon> page1 = couponService.selectAll(coupon);
        model.addAttribute("page", page1);
        return "coupon";
    }*/
}
